package org.linlinjava.litemall.wx.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.constant.CommissionConstant;
import org.linlinjava.litemall.db.domain.LitemallCommission;
import org.linlinjava.litemall.db.domain.LitemallCommissionApply;
import org.linlinjava.litemall.db.domain.LitemallCommissionLog;
import org.linlinjava.litemall.db.domain.LitemallOrderCommission;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.vo.PageVO;
import org.linlinjava.litemall.db.vo.UserCommissionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Random;

/**
 * 佣金管理
 */
@Slf4j
@RestController
@RequestMapping("/wx/commission")
@Api(description = "用户佣金管理")
public class WxCommissionController {
    @Autowired
    private LitemallOrderCommissionService orderCommissionService;
    @Autowired
    private LitemallCommissionLogService commissionLogService;
    @Autowired
    private LitemallCommissionService commissionService;
    @Autowired
    private LitemallCommissionApplyService commissionApplyService;
    @Autowired
    private LitemallSystemConfigService configService;

    @ResponseBody
    @PostMapping("queryLog")
    @ApiOperation(value = "佣金变动日志查询", httpMethod = "POST")
    public Object queryLog(@RequestBody PageVO<LitemallCommissionLog, LitemallCommissionLog> pageVO) {
        List<LitemallCommissionLog> list = commissionLogService.queryByExample(pageVO);
        return ResponseUtil.okList(list);
    }

    @ResponseBody
    @PostMapping("queryOrder")
    @ApiOperation(value = "佣金发放日志查询", httpMethod = "POST")
    public Object queryOrder(@RequestBody PageVO<LitemallOrderCommission, LitemallOrderCommission> pageVO) {
        List<LitemallOrderCommission> list = orderCommissionService.queryByExample(pageVO);
        return ResponseUtil.okList(list);
    }

    @ResponseBody
    @PostMapping("apply")
    @ApiOperation(value = "佣金提现申请", httpMethod = "POST")
    public Object commissionApply(@RequestBody LitemallCommissionApply commissionApply) {
        try {
            String applyMin = SystemConfig.getLitemallCommissionApplyMin();
            String applyMax = SystemConfig.getLitemallCommissionApplyMax();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
            String now = df.format(LocalDate.now());
            String orderSn = now + getRandomNum(6);
            commissionApply.setCode(orderSn);
            commissionApply.setBankType(CommissionConstant.APPLY_BANK.get(commissionApply.getBankCode()));
            if (commissionApply.getUserId() == null) {
                return ResponseUtil.unlogin();
            }
            if (StringUtils.isEmpty(commissionApply.getBankCode())) {
                return ResponseUtil.fail("400", "请选择提现方式");
            }
            if (StringUtils.isEmpty(commissionApply.getAccount())) {
                return ResponseUtil.fail("400", "请录入收款账号");
            }
            if (StringUtils.isEmpty(commissionApply.getCommission()) || commissionApply.getCommission().compareTo(new BigDecimal(0)) == 0) {
                return ResponseUtil.fail("400", "请录入提现金额");
            } else if (commissionApply.getCommission().compareTo(new BigDecimal(applyMin)) < 0 || commissionApply.getCommission().compareTo(new BigDecimal(applyMax)) > 0) {
                return ResponseUtil.fail("400", "提现金额应在" + applyMin + "-" + applyMax + "元之间");
            }
            commissionApply.setCreatedTime(LocalDateTime.now());
            commissionApply.setUpdatedTime(LocalDateTime.now());
            commissionApply.setStatus(CommissionConstant.APPLY_DEFAULT);
            commissionApply.setDeleted("0");
            int result = commissionApplyService.save(commissionApply);
            if (result < 0) {
                return ResponseUtil.serious();
            }
            return ResponseUtil.ok();
        } catch (Exception e) {
            log.error("提现申请保存异常：" + e);
            return ResponseUtil.serious();
        }
    }

    @ResponseBody
    @GetMapping("applyConfig")
    @ApiOperation(value = "佣金提现配置查询", httpMethod = "GET")
    public Object commissionApply() {
        try {
            return ResponseUtil.ok(configService.listCommission());
        } catch (Exception e) {
            log.error("佣金提现配置查询异常：" + e);
            return ResponseUtil.serious();
        }
    }

    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    @ResponseBody
    @PostMapping("queryApply")
    @ApiOperation(value = "佣金提现记录查询", httpMethod = "POST")
    public Object commissionApply(@RequestBody PageVO<LitemallCommissionApply, LitemallCommissionApply> pageVO) {
        try {
            if (pageVO.getCondition() == null || pageVO.getCondition().getUserId() == null) {
                return ResponseUtil.unlogin();
            }
            List<LitemallCommissionApply> list = commissionApplyService.queryByExample(pageVO);
            if (list == null) {
                return ResponseUtil.serious();
            }
            return ResponseUtil.okList(list);
        } catch (Exception e) {
            log.error("提现申请记录查询异常：" + e);
            return ResponseUtil.serious();
        }
    }

    @ResponseBody
    @PostMapping("queryUserCommission")
    @ApiOperation(value = "会员佣金情况查询", httpMethod = "POST")
    public Object queryUserCommission(@RequestParam Integer userId) {
        try {
            if (userId == null) {
                return ResponseUtil.unlogin();
            }
            UserCommissionVO commissionVO = new UserCommissionVO();
            LitemallCommission commission = commissionService.queryByUserId(userId);
            commissionVO.setCommission(commission.getCurrentCommission());
            commissionVO.setUsername(commission.getUsername());
            PageVO<LitemallCommissionLog, LitemallCommissionLog> pageVO = new PageVO<LitemallCommissionLog, LitemallCommissionLog>();
            LitemallCommissionLog log = new LitemallCommissionLog();
            //查询用户过去提现
            log.setUserId(userId);
            log.setType("1");
            pageVO.setCondition(log);
            List<UserCommissionVO> apply = commissionLogService.queryUserCommission(pageVO);
            if (apply != null && !apply.isEmpty()) {
                commissionVO.setApply(apply.get(0).getApply());
            } else {
                commissionVO.setApply(new BigDecimal(0));
            }
            //昨日收益
            log.setType("0");
            pageVO.setBeginTime(LocalDateTime.now().minus(1, ChronoUnit.DAYS));
            pageVO.setEndTime(LocalDateTime.now());
            List<UserCommissionVO> income = commissionLogService.queryUserCommission(pageVO);
            if (income != null && !income.isEmpty()) {
                commissionVO.setIncome(income.get(0).getIncome());
            } else {
                commissionVO.setIncome(new BigDecimal(0));
            }
            return ResponseUtil.ok(commissionVO);
        } catch (Exception e) {
            log.error("提现申请记录查询异常：" + e);
            return ResponseUtil.serious();
        }
    }

}
